package com.example.demo.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.Principal;

/**
 * @author CoderJia
 * @create 2024/10/13 下午 02:10
 * @Description
 **/
@Slf4j
@Controller
public class LoginController {

    @GetMapping("/login")
    public String login() {
        return "login";  // 返回名为 "login" 的模板或 HTML 页面
    }


    @GetMapping("/index")
    public String home(Principal principal) {
        log.info("index"+principal.getName());
        return "index";  // 返回名为 "index" 的模板或 HTML 页面
    }

    @ResponseBody
    @GetMapping("/admin")
    public String admin() {
        log.info("admin");
        return "欢迎进入管理页面";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        log.info("logout");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return "redirect:/login?logout"; // 重定向到登录页面
    }
}

